import Tips from '../util/Tips.js'
// 保存图片到相册中
function savePicture(url) {
	// #ifdef APP-PLUS
	const path = plus.io.convertLocalFileSystemURL(url)
	plus.gallery.save(path, () => {
		Tips.success('保存相册成功','none')
	}, (error) => {
		console.debug('保存相册失败', error, path)
		Tips.error('保存相册失败')
	});
	// #endif
	
	// #ifdef MP
	uni.authorize({
		// #ifdef MP-WEIXIN
		scope:'scope.writePhotosAlbum',
		// #endif
		// #ifdef MP-TOUTIAO
		scope: 'scope.album',
		// #endif
		success(res) {
			uni.saveImageToPhotosAlbum({
				filePath: url,
				success: e=> {
					Tips.toast('保存图片成功！')
				},
				fail: e => {
					console.debug(e)
					Tips.toast('保存图片失败')
				}
			})
		},
		fail(e) {
			Tips.confirm({
				content: '检测到您没打开下载图片功能权限，是否去设置打开？',
				showCancel: true,
			}).then(res => {
				if(!res) return;
				uni.openSetting({
				  success: (sRes) => {}
				})
			})
		}
	})
	// #endif
}


import {
	os_name
} from '../data/staticData.js'

function copyText(text) {
	// #ifdef APP-PLUS
	if (os_name == "Android") {
		var Context = plus.android.importClass("android.content.Context");
		var main = plus.android.runtimeMainActivity();
		var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
		plus.android.invoke(clip, "setText", text);
	} else if (os_name == "iOS") {
		var UIPasteboard = plus.ios.importClass("UIPasteboard");
		var generalPasteboard = UIPasteboard.generalPasteboard();
		//设置/获取文本内容:
		generalPasteboard.plusCallMethod({
			setValue: text,
			forPasteboardType: "public.utf8-plain-text"
		});
		generalPasteboard.plusCallMethod({
			valueForPasteboardType: "public.utf8-plain-text"
		});
	}
	// #endif
}

// 拍照
function captureImage() {
	return new Promise((reslove, reject) => {
		// #ifdef APP-PLUS
		var cmr = plus.camera.getCamera();
		var res = cmr.supportedImageResolutions[0];
		var fmt = cmr.supportedImageFormats[0];
		console.debug("Resolution: " + res + ", Format: " + fmt);
		cmr.captureImage(function(path) {
				console.debug("captureImage image success: " + path);
				reslove(path)
			},
			function(error) {
				reject(error.message)
				console.debug("Capture image failed: " + error.message);
			}, {
				resolution: res,
				format: fmt
			}
		);
		// #endif
	}).catch((e) => {});

}

// 从相册中选择图片 
function galleryImg() {
	return new Promise((reslove, reject) => {
		// #ifdef APP-PLUS
		// 从相册中选择图片
		console.debug("从相册中选择图片:");
		plus.gallery.pick(function(path) {
			console.debug("galleryImg image success: " + path);
			reslove(path)
		}, function(e) {
			reject(e)
			console.debug("取消选择图片");
		}, {
			filter: "image"
		});
		// #endif
	}).catch((e) => {});
}


//压缩图片
function compressImage(url, filename) {
	return new Promise((reslove, reject) => {
		// #ifdef APP-PLUS
		var name = "_doc/" + filename;
		plus.zip.compressImage({
				src: url, //src: (String 类型 )压缩转换原始图片的路径
				dst: name, //压缩转换目标图片的路径    
				quality: 90, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100    
				overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
				width: '62px',
				height: '62px',
			},
			function(event) {
				console.debug("Compress success!");
				reslove(event.target)
				// plus.io.resolveLocalFileSystemURL(event.target, (entry) => {
				// 	console.debug('showPics压缩图片成功')
				// 	entry.file((file) => {
				// 		reslove(file)
				// var fileReader = new plus.io.FileReader();
				// fileReader.readAsDataURL(file);
				// fileReader.onloadend = (e) => {
				// 	var picUrl = e.target.result.toString();
				// 	console.debug('picUrl', picUrl)
				// 	reslove(picUrl)
				// }
				// 	});
				// });
			},
			function(error) {
				reject(error)
				console.debug("Compress error!");
			});
		// #endif
	}).catch((e) => {});
}

// 获取系统 应用通知权限配置
function getNotificationSetting() {
	return new Promise((resolve, reject) => {
		// #ifdef APP-PLUS
		let notificationSetting;
		if (os_name == 'Android') {
			let main = plus.android.runtimeMainActivity();
			let pkName = main.getPackageName();
			// let NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat"); 
			let notificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
			let packageNames = notificationManagerCompat.from(main);
			notificationSetting = {
				main,
				pkName,
				packageNames
			}
		} else {
			// ios不做任何操作
			notificationSetting = {}
		}
		resolve(notificationSetting)
		// #endif
	})
}
// 判断应用的通知权限是否打开
function checkNotification(setting) {
	if (!setting) return false;
	// #ifdef APP-PLUS
	if (os_name == 'Android') {
		return !setting.packageNames.areNotificationsEnabled()
	} else {
		// ios获取是否开启权限
		var UIApplication = plus.ios.import("UIApplication");
		var app = UIApplication.sharedApplication();
		let enabledTypes = 0;
		if (app.currentUserNotificationSettings) {
			let settings = app.currentUserNotificationSettings();
			enabledTypes = settings.plusGetAttribute("types");
			plus.ios.deleteObject(settings);
		} else {
			enabledTypes = app.enabledRemoteNotificationTypes();
		}
		plus.ios.deleteObject(app);
		plus.ios.deleteObject(UIApplication);
		return enabledTypes == 0;
	}
	// #endif
}

// 打开系统通知权限设置页面
function openNotificationSetting(setting) {
	if (!setting) return false;
	// #ifdef APP-PLUS
	if (os_name == 'Android') {
		let uid = setting.main.getApplicationInfo().plusGetAttribute("uid");
		let Intent = plus.android.importClass('android.content.Intent');
		let Build = plus.android.importClass("android.os.Build");
		let intent;
		//android 8.0引导
		if (Build.VERSION.SDK_INT >= 26) {
			intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
			intent.putExtra('android.provider.extra.APP_PACKAGE', setting.pkName);
		} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
			intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
			intent.putExtra("app_package", setting.pkName);
			intent.putExtra("app_uid", uid);
		} else { //(<21)其他--跳转到该应用管理的详情页
			let Settings = plus.android.importClass("android.provider.Settings");
			let Uri = plus.android.importClass("android.net.Uri");
			intent = new Intent();
			intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
			let uri = Uri.fromParts("package", setting.pkName, null);
			intent.setData(uri);
		}
		// 跳转到该应用的系统通知设置页  
		setting.main.startActivity(intent);
	} else {
		// ios跳转到权限页
		let UIApplication = plus.ios.import("UIApplication");
		let NSURL2 = plus.ios.import("NSURL");
		let setting2 = NSURL2.URLWithString("app-settings:");
		let application2 = UIApplication.sharedApplication();
		application2.openURL(setting2);
		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	}
	// #endif
}

// 触感反馈
function touchFeedBack() {
	// #ifdef APP-PLUS
	if (os_name == 'Android') {
		plus.device.vibrate(50);
	} else {
		// plus.device.vibrate(50);
	}
	// #endif
}

module.exports = {
	compressImage,
	galleryImg,
	savePicture,
	captureImage,
	copyText,
	getNotificationSetting,
	checkNotification,
	openNotificationSetting,
	touchFeedBack,
}
